//点击图片更换验证码
function updateVeryCode(){
    $("#captchaImg").attr('src' ,'/captcha-image?'+ Math.floor(Math.random()*100));
}
function focusInput(objOrSelector) {
    let target = $(objOrSelector);
    target.parent().parent().addClass("current");
    let msgBox = target.parent().find("span");
    msgBox.html("");
    msgBox.removeClass();
}

function setWarnPrompt(objOrSelector,prompt) {
    let target = $(objOrSelector);
    target.parent().parent().removeClass();
    let msgBox = target.parent().find("span");
    msgBox.html(prompt);
    msgBox.addClass("error");
}

function checkAndWarnInput(objOrSelector, item,compareSelector) {
    let target = $(objOrSelector);
    if (target.val() === "") {
        setWarnPrompt(objOrSelector, item + "不能为空");
        return false;
    } else if (isStringNotEmpty(compareSelector) && $(compareSelector).val() !== target.val()) {
        setWarnPrompt(objOrSelector,"两次输入的密码不相同");
        return false;
    }
    return true;
}

function checkAndWarnUserName() {
    return checkAndWarnInput("#userName","用户名");
}

function checkAndWarnPassword() {
    return checkAndWarnInput("#passWord","登录密码");
}

function checkAndWarnVeryCode() {
    return checkAndWarnInput("#veryCodeTxt", "验证码");
}

function checkAndWarnConfirmPassword() {
    return checkAndWarnInput("#rePassWord","确认密码","#passWord");
}

function checkUserInput() {
    if (!checkAndWarnUserName()) {
        return false;
    }
    if (!checkAndWarnPassword()) {
        return false;
    }
    return checkAndWarnVeryCode();
}

function onLoginClick() {
    if (!checkUserInput()) {
        return;
    }
    const userName = $("#userName").val();
    const password = $("#passWord").val();
    const veryCode = $("#veryCodeTxt").val();
    const passwordMd5 = hex_md5(password);
    $.ajax({
            url: URL_HEAD_MEMBER + "/login",
            //通过type来判断调用哪个方法
            type: "post",
            headers: {
                "captcha": veryCode
            },
            data: {
                "uname": userName,
                "password": passwordMd5
            },
            dataType: "json",
            success: function (result) {
                // alert(JSON.stringify(result));
                if (result.status === 0) {
                    localStorage.setItem(ITEM_KEY_USER_NAME, userName);
                    //登录成功，保存token
                    const tokenValue = result.data;
                    localStorage.setItem(ITEM_KEY_TOKEN_VALUE, tokenValue);
                    const parameters = tokenValue.split("-");
                    localStorage.setItem(ITEM_KEY_USER_ID, parameters[0]);
                    const userRole = parameters[1];
                    localStorage.setItem(ITEM_KEY_USER_ROLE, userRole);
                    if (userRole === ROLE_USER) {
                        $(location).attr("href", "index.html");
                    } else {
                        $(location).attr("href", "manae\\index.html");
                    }
                }else if(result.status === -1) {
                    setWarnPrompt("#veryCodeTxt", "验证码错误");
                } else if (result.status === 1) {
                    alert(result.msg);
                    $(location).attr("href", "register.html");
                } else if (result.status === 2) {
                    setWarnPrompt("#passWord", result.msg);
                } else if (result.status === 3) {
                    alert(result.msg);
                }
            },
            error:function(xhr, textStatus, errorThrown) {
                showError("登录异常",xhr,textStatus,errorThrown);
            }
    })
}

function onRegisterClick() {
    if (!checkUserInput()) {
        return;
    }
    if (!checkAndWarnConfirmPassword()){
        return;
    }
    const userName = $("#userName").val();
    const password = $("#passWord").val();
    const veryCode = $("#veryCodeTxt").val();
    const passwordMd5 = hex_md5(password);
    $.ajax({
        url: URL_HEAD_MEMBER + "/register" ,
        //通过type来判断调用哪个方法
        type:"post",
        headers: {
            "captcha":veryCode
        },
        data:{
            "uname":userName,
            "password":passwordMd5
        },
        dataType:"json",
        success:function (result) {
            if (result.status === -1) {
                setWarnPrompt("#veryCodeTxt","验证码错误");
            }else {
                alert(result.msg);
                if (result.status === 0) {
                    //跳转到登录页面
                    $(location).attr("href", "login.html");
                }
            }
        },
        error:function (xhr, textStatus,errorThrown) {
            showError("注册异常", xhr, textStatus, errorThrown);
        }
    });
}
function onLogoutClick() {
    alert("on logout");
    $.ajax({
        url: URL_HEAD_MEMBER + "logout",
        //通过type来判断调用哪个方法
        type: "post",
        data: {
            "tokenValue": localStorage.getItem(ITEM_KEY_TOKEN_VALUE)
        },
        dataType: "json",
        success: function (result) {
            clearCache();
            $(location).attr("href", "index.html");
        },
        error: function (xhr, textStatus, errorThrown) {
            showError("退出登录异常", xhr, textStatus, errorThrown);
        }
    });
}
function clearCache() {
    localStorage.removeItem(ITEM_KEY_USER_NAME);
    localStorage.removeItem(ITEM_KEY_USER_ID);
    localStorage.removeItem(ITEM_KEY_USER_ROLE);
    localStorage.removeItem(ITEM_KEY_USER_NAME);
}

function onUserLoad(){
    $.ajax({
        url:URL_HEAD_MEMBER+"/list",
        type : "get",
        success: function(result) {
            const userCount = result.data.length;
            if (userCount > 0) {
                const builder = new StringBuilder();
                for (let i = 0; i < userCount; i++) {
                    const user = result.data[i];
                    addUserTableNewRow(user, builder);
                    console.log(user)
                }
            }
        },
        error:function(xhr, textStatus, errorThrown) {
            showError("导入用户管理失败", xhr, textStatus, errorThrown);
        }
    });
}

function addUserTableNewRow(user, builder){
    builder.clear()
    builder.append("<tr><td class='first w4 c'>");
    builder.append(user.memberId)
    builder.append("</td><td class='w1 c'>");
    builder.append(user.uname);
    builder.append("</td><td class='w1 c'>");
    builder.append(user.sex);
    builder.append("</td><td>");
    builder.append(user.email);
    builder.append("</td><td class='w1 c'>");
    builder.append(user.mobile);
    builder.append("</td><td class='w1 c'><a href='user-modify.html?id=");
    builder.append(user.memberId)
    builder.append("'>修改</a> <a href='javascript:Delete(1);'>删除</a></td>");
    $("#tbUserManage tr:last").after(builder.toString());
}








